﻿namespace assignment4_2
{
    public delegate void TickHandler(object sender, TickEventArgs args);

    public delegate void AlarmHandler(object sender, AlarmEventArgs args);

    public class TickEventArgs : EventArgs
    {
        public DateTime CurrentTime { get; set; }
    }

    public class AlarmEventArgs : EventArgs
    {
        public DateTime AlarmTime { get; set; }
    }

    public class AlarmClock
    {
        private DateTime currentTime;
        private DateTime alarmTime;
        private bool alarmTriggered;

        public event TickHandler OnTick;

        public event AlarmHandler OnAlarm;

        public AlarmClock()
        {
            currentTime = DateTime.Now;
            alarmTriggered = false;
        }

        public void SetAlarmTime(DateTime time)
        {
            alarmTime = time;
            alarmTriggered = false;
        }

        public void Start()
        {
            while (true)
            {
                Thread.Sleep(1000);//模拟1秒的流逝

                currentTime = currentTime.AddSeconds(1);

                OnTick(this, new TickEventArgs { CurrentTime = currentTime });

                if (!alarmTriggered && currentTime >= alarmTime)
                {
                    OnAlarm(this, new AlarmEventArgs { AlarmTime = alarmTime });
                    alarmTriggered = true;
                }
            }
        }
    }

    public class AlarmForm
    {
        public AlarmClock clock = new AlarmClock();

        public AlarmForm()
        {
            clock.OnTick += new TickHandler(Clock_OnTick);
            clock.OnAlarm += Clock_OnAlarm;
        }

        private void Clock_OnTick(object sender, TickEventArgs args)
        {
            Console.WriteLine($"时钟滴答：{args.CurrentTime:HH:mm:ss}");
        }

        private void Clock_OnAlarm(object sender, AlarmEventArgs args)
        {
            Console.WriteLine($"闹钟响了!");
        }
    }

    internal class Program2
    {
        private static void Main(string[] args)
        {
            AlarmForm myAlarm = new AlarmForm();
            myAlarm.clock.SetAlarmTime(DateTime.Now.AddSeconds(10));
            Console.WriteLine("闹钟已设置，10秒.");
            myAlarm.clock.Start();
        }
    }
}